package com.lysj.admin.master.common.enumeration;

import com.lysj.admin.master.CacheManager;
import com.lysj.admin.master.common.CommonConstant;
import com.lysj.admin.master.common.web.SelectItem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Created by zk on 2019-05-17 14:42
 * @description 枚举工具类
 */
public class EnumUtils {

//    private static Cache<String, Map<Integer, String>> enumInterfaceMapCache = CacheUtil.newLRUCache(100);


    /**
     * @author Created by zk on 2019/11/28 18:52
     * @Description 通过枚举类构造 码-描述 的集合
     */
    public static <T extends EnumInterface> List<SelectItem> createEnumSelectItem(Class<T> tClass) {
        List<SelectItem> selectItems = new ArrayList<>();
        for (T t : tClass.getEnumConstants()) {
            selectItems.add(new SelectItem<>(t.getCode(), t.getStatus()));
        }
        return selectItems;
    }

    /**
     * @author Created by zk on 2019/11/28 18:51
     * @Description 通过枚举码和枚举类找出枚举描述
     */
    public static <T extends EnumInterface> String findStatusByCode(Integer code, Class<T> tClass) {
        final String s = findStatus(code,tClass);
        if(s == null){
            return CommonConstant.UNKNOWN;
        }
        return s;
    }


    /**
     * @author Created by zk on 2019/11/28 18:53
     * @Description 通过枚举码和枚举类型，判断该枚举码是否存在
     */
    public static <T extends EnumInterface> boolean checkCode(Integer code, Class<T> tClass){
        final String s = findStatus(code,tClass);
        return s != null;
    }

    private static <T extends EnumInterface> String findStatus(Integer code, Class<T> tClass){
        Map<Integer, String> map = CacheManager.ENUM_UTILS.get(tClass.getName(),() -> {
            Map<Integer, String> em = new HashMap<>();
            for (T t : tClass.getEnumConstants()) {
                em.put(t.getCode(), t.getStatus());
            }
            return em;
        });
        return map.get(code);
    }
}
